<?php

function duoshuo($tid,$title = '' , $url = ''){

$title = ''; // 可以根据tid查询
$url   = ''; // 可以根据tid生成
echo '
<div class="ds-thread" data-thread-key="'.$tid.'" data-title="'.$title.'" data-url="'.$url.'"></div>
<script type="text/javascript">
var duoshuoQuery = {short_name:"missql-blog"};
(function() {
	var ds = document.createElement("script");
	ds.type = "text/javascript";ds.async = true;
	ds.src = (document.location.protocol == "https:" ? "https:" : "http:") + "//static.duoshuo.com/embed.js";
	ds.charset = "UTF-8";
	(document.getElementsByTagName("head")[0] 
	 || document.getElementsByTagName("body")[0]).appendChild(ds);
})();
</script>
';

}

/**
 * 生成缩略图
 * @param  [type] $img     [description]
 * @param  [type] $width   [description]
 * @param  [type] $height  [description]
 * @param  [type] $quality [description]
 * @param  [type] $cut 	   [是否居中裁剪]
 * @return [type]          [description]
 */
function thumb_img( $img_src,$width = 240 ,$height = 240 ,$quality = 100 , $cut = 0){
	// 可以在配置文件里配置
	$thumb_path = C('THUMB_PATH')?C('THUMB_PATH'):'data/thumb/';  
	require_once 'Class/ResizeImage.class.php';
	$name_arr   = explode('/', $img_src);	// 分割取出文件名
	$img_name   = $name_arr[count($name_arr)-1];	// 文件名

	$img_name_arr = explode('.', $img_name); // 分割取出不带格式的文件名
	$thumb_name = $img_name_arr[0].'_'.$width."x".$height.'q='.$quality.'c='.$cut.'.'.$img_name_arr[1];	// 缩略图文件名
	$thumb_file_path = $thumb_path.$thumb_name;	// 缩略图存储地址 
	// 判断缩略图是否已经存在
	if(file_exists($thumb_file_path)){
		echo '/'.$thumb_file_path;
	}else{
		// 处理 路径问题
		// echo $img_src;
		$img_src = ltrim($img_src,'/');
		$resizeimage = new ResizeImage($img_src, $width, $height, $cut, $thumb_file_path,0,$quality);
		echo '/'.$thumb_file_path;
	}
}


/**
 * 生成html
 * @param [type]  $tid [description]
 * @param integer $num [description]
 */
function create_list_html($tid,$num = 5){
	$list = get_article_list($tid,$num);
	$html = '';
	if(empty($list)){
		$html .= '<li>暂无相关内容</li>';
	}
	foreach ($list as $key => $value) {
		$html .= '<li>&nbsp;&nbsp;•&nbsp;&nbsp;<a href="/article/'.$value['id'].'.html">'.utf8Substr($value['post_title'],0,18).'</a>'.is_new($value['create_time'],1).'<span>'.date('Y-m-d',$value['create_time']).'</span></li>';
	}
	echo $html;
}



/**
 * 生成列表链接
 * @param [type] $vo [description]
 */
function set_list_url($vo){
	echo "/article/list/".$vo['term_id'].'.html';
}

/**
 * 生成文章链接
 * @param [type] $vo [description]
 */
function set_article_url($vo){
	echo "/article/".$vo['ID'].'.html';
}


/**
 * 截取文章内容
 * @param  [type]  $data [description]
 * @param  integer $cut  [description]
 * @param  string  $str  [description]
 * @return [type]        [description]
 */
function cutArticle($data,$cut=0,$str="....")
{	
	
	$data=strip_tags($data);//去除html标记
	$pattern = "/&[a-zA-Z]+;/";//去除特殊符号
	$data=preg_replace($pattern,'',$data);
	if(!is_numeric($cut))
		return $data;
	if($cut>0)
		$data=utf8Substr($data,0,$cut);
	
	return $data;
}


/**
 * 连本目录也删除
 * @param  [type] $dirName [description]
 * @return [type]          [description]
 */
function delDirAndFile( $dirName )  {  
	if ( $handle = opendir( "$dirName" ) ) {  
	   while ( false !== ( $item = readdir( $handle ) ) ) {  
	   if ( $item != "." && $item != ".." ) {  
	   if ( is_dir( "$dirName/$item" ) ) {  
	   delDirAndFile( "$dirName/$item" );  
	   } else {  
	   if( unlink( "$dirName/$item" ) )echo "成功删除文件： $dirName/$item<br />\n";  
	   }  
	   }  
	   }  
	   closedir( $handle );  
	   if( rmdir( $dirName ) )echo "成功删除目录： $dirName<br />\n";  
	}  else{
		echo 'error';
	}
} 

/**
 * 只删除文件
 * @param  [type] $dir [description]
 * @return [type]      [description]
 */
function deldir($dir) {
  //先删除目录下的文件：
  $dh = opendir($dir);
  while ($file=readdir($dh)) {
    if($file!="." && $file!="..") {
      $fullpath=$dir."/".$file;
      if(!is_dir($fullpath)) {
          unlink($fullpath);
          echo '删除 '.$fullpath.' 成功!<br>';
      } else {
          deldir($fullpath);
      }
    }
  }
 
  closedir($dh);
}

/**
 * [getSize description]
 * @param  [type] $size [description]
 * @return [type]       [description]
 */
function getSize($size = 0,$type = 'kb'){
	if(strtolower($type) == 'kb'){
		return number_format( $size/1024 , 0);
	}
	if(strtolower($type) == 'mb'){
		return number_format( $size/2048 , 0);
	}
}
/**
 * 简单获取单条信息
 * @return [type] [description]
 */
// function get_info($db = '' , $map = array() , $field = '*' , $order = '' , $type = 1 ){

// 	if(empty($db)) return -2;
// 	if($type == 1){
// 		if(is_int($map)){
// 			// echo $map;
// 			return M($db)->where('id='.$map)->field($field)->order($order)->find();
// 		}
// 		else
// 			return M($db)->where($map)->field($field)->order($order)->find();
// 	}else{
// 		if(is_int($map)){
// 			// echo $map;
// 			return M($db)->where('id='.$map)->field($field)->order($order)->getField($field);
// 		}
// 		else
// 			return M($db)->where($map)->field($field)->order($order)->getField($field);
// 	}

// }

// function get_info(){
// 	return 1;
// }

function get_terms($parent = 0){
	
	$list = M('terms')->where("parent = $parent")->order('listorder')->select();
	return $list;
}


function get_parents( $id , $arr = array() ){

    $term = M('terms')->field('term_id as id,name,parent,url_name,taxonomy')->where("term_id = $id")->find();
    
    $arr[] = $term;

    if($term['parent'] != 0){

        $arr = array_merge($arr , $parent = get_parents($term['parent']) );

    }  
    foreach ($arr as $key => $value) {
    	$arr[$key]['href'] = U($value['taxonomy'].'/'.$value['url_name']);
    }
    return array_reverse($arr);

} 


/**
 * 获取递归带文章的导航
 * @param  integer $limit [description]
 * @return [type]         [description]
 */
function get_nav_and_posts($limit = 10 , $fields = 'id,post_title'){
	require_once 'Class/Unlimited.class.php';
	$terms = M('terms')->order('listorder')->select();
	$terms = Unlimited::unlimitedForNav($terms , 'item' , 'parent');
	// pe($terms);
	foreach ($terms as $key => $value) {
		$terms[$key]['posts'] = M('posts')
			->where("term_id = ".$value['term_id'])
			->field($fields)
			->order('post_date DESC')
			->limit($limit)
			->select();
	}
	return $terms;
}



/**
 * 获取分类列表
 * @return [type] [description]
 */
function get_cate(){
	$list = M('terms')->where('parent = 0')->order('listorder')->select();

	return $list;
}

function get_unlimited_cate(){
	$list = M('terms')->where('')->order('listorder')->select();

	require_once 'Class/Unlimited.class.php';
	$list = Unlimited::unlimitedForNav($list,'item','term_id','parent');
	// pe($list);
	return $list;
}

/**
 * 获取递归导航
 * @return [type] [description]
 */
function get_nav($cid = 1 , $cache_name = 'nav' , $time ){

	// if(S($cache_name)){
	// if(S($cache_name)){
	// 	return S($cache_name);
	// }else{
		$lists = M('nav')->where('cid = '.$cid)->order('listorder')->select();
		// print_r($lists);
		foreach ($lists as $key => $value) {
			$lists[$key]['href'] 	 = get_href($value['href']);
			$lists[$key]['location'] = get_location($value['href']);
		}
		require_once 'Class/Unlimited.class.php';
		$nav = Unlimited::unlimitedForNav($lists , 'item' , 'parentid');

		S($cache_name , $nav , $time?$time:C('CACHE_NAV_TIME'));
		return $nav;
	// }

}

function get_location($href){
	$href    = unserialize(stripslashes($href));
	return $href['param']['id'];
}

function get_href($nav_href){
	$href    = $nav_href;
	$hrefold = $href;
	$href    = unserialize(stripslashes($nav_href));
	// p($href);

	if(empty($href)){
		if($hrefold=="home"){
			$href=__ROOT__."/";
		}else{
			$href=$hrefold;
		}
	}else{
		$default_app = strtolower(C("DEFAULT_GROUP"));
		// p($href);
    // [action] => Portal/List/index
    // [param] => Array
    //     (
    //         [id] => 54
    //     )
    	$action = explode('/', $href['action']);
		// $href        = U($href['action'],$href['param']);
		$url_name = M('terms')->where("term_id = ".$href['param']['id'])->getField('url_name');
		$taxonomy = M('terms')->where("term_id = ".$href['param']['id'])->getField('taxonomy');

		// $href        = U( '/'.strtolower($action[1]).'/'.$href['param']['id']);
		// 列表页
		// SITE_DOMAIN.
		if(strtolower($action[1]) == 'list'){
			// $href = U( "/$taxonomy/$url_name");
			// $href = U( "/$taxonomy/list/".$href[param][id]);
			$href = U( "/article/list/".$href[param][id]);
			// $href = U( "/$url_name/list");
		}else{
			// Page页
			$href        = U( '/'.strtolower($action[1]).'/'.$href['param']['id']);
		}
		// exit;

		$g 			 = C("VAR_GROUP");
		$href        = preg_replace("/\/$default_app\//", "/",$href);
		$href 		 = preg_replace("/$g=$default_app&/", "",$href);
		// $href['location'] = $href['param']['id'];
	}
	return $href;
}

function check_active($vo,$location){
// <if condition="$vo['attr_id'] == $location">class="active"</if>
	if(empty($vo['location'])){
		if($vo['attr_id'] == $location){
			echo 'class="active"';
		}
	}else{
		if($vo['location'] == $location){
			echo 'class="active"';
		}
	}
}

/**
 * 获取幻灯片
 * @return [type] [description]
 */
function get_slide($slide_cid = 1 ,$limit = 10){
	if($limit == 1){
		$lists =  M('slide')
		->where("slide_cid = $slide_cid and slide_status <> 0")
		->order('listorder')
		->limit($limit)
		->find();
	}else{
		$lists = M('slide')
			->where("slide_cid = $slide_cid and slide_status <> 0")
			->order('listorder')
			->limit($limit)
			->select();
	}

	// print_r($lists);exit;
	return $lists;
}


/**
 * 获取单独图片
 * @return [type] [description]
 */
function get_slide_byid($slide_id = 1){
	$info =  M('slide')->where("slide_id = $slide_id and slide_status <> 0")->find();
	// print_r($lists);exit;
	return $info;
}

/**
 * 获取友情链接
 * @return [type] [description]
 */
function get_friend_link($num = 20){
	$lists = M('links')->order('listorder')->limit($num)->select();
	return $lists;
}

/**
 * 获取某栏目下的文章列表
 * 也要做Cache
 * $field='p.id,p.view,p.post_title,p.post_excerpt,p.smeta,tr.tid'
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
function get_article_list($term_id, $limit = 6, $field = 'id,term_id,view,post_title,post_excerpt,smeta,create_time,color', $order = 'post_date DESC' , $exclude_id = 0 , $get_term_info = false) {
    if ($field == 'init') {
        $field = 'id,term_id,view,post_title,post_excerpt,smeta,create_time,color';
    }
    $s_md5 = md5($term_id . $limit . $field . $order);
    $Cache = Cache::getInstance('File', array(
        'expire' => '60'
    ));
    $Cache->setOptions('Temp', 'ThinkPHP');
    // $Cache->set('name','ThinkPHP');
    if ($Cache->get($s_md5)) {
        $lists = $Cache->get($s_md5);
    } else {
        // 不存在
        $map['status'] = array('NEQ',0);
        if (!empty($term_id)) {
            if (!is_int($term_id)) {
                $map['term_id'] = array('IN',explode(',', $term_id));
            } else {
                $map['term_id'] = $term_id;
            }
        }
        if($exclude_id) $map['ID'] = array('NEQ',$exclude_id);

        $lists = M('posts')->where($map)->field($field)->order($order)->limit($limit)->select();
        // 关联查询
        foreach ($lists as $key => $value) {
            if($get_term_info){
            	$lists[$key]['term'] = M('terms')->where('term_id = ' . $value['term_id'])->find();
            }
        }
        $lists = parsing_json($lists);
        $Cache->set($s_md5, $lists, 60);
        return $lists;
    }
}


function get_article($id,	$field = 'id,term_id,view,post_title,post_excerpt,post_content,smeta,create_time'){
	return M('posts')->field($field)->where("id = $id")->find();
}

function get_list($db,$map='',$order ='',$limit = 10){
	return M($db)->where($map)->order($order)->limit($limit)->select();
}
/**
 * 获取人气排行
 * @param  string  $term_id [description]
 * @param  integer $limit   [description]
 * @return [type]           [description]
 */
function get_view_rank($term_id = '' , $limit = 10){

	if($term_id){
		$lists = M('posts')
			->where("term_id = $term_id and status <> 0 ")
			->field('id,view,post_title,smeta')
			->order('view DESC')
			->limit($limit)
			->select();
	}else{
		$lists = M('posts')
			->where("status <> 0")
			->field('id,view,post_title,smeta')
			->order('view DESC')
			->limit($limit)
			->select();
	}
	return parsing_json($lists);
}

/**
 * 获取随机推荐
 * @return [type] [description]
 */
function get_random_post(){
	$list = get_view_rank('',10);
	$num = rand(0,(count($list)-1));
	return $list[$num];
}

/**
 * 解析图片json
 * @param  [type] $list [description]
 * @return [type]       [description]
 */
function parsing_json($list){
	foreach ($list as $key => $value) {
		$list[$key]['images'] = json_decode($value['smeta'],true);
	}
	return $list;
}


/**
 * 有云存储时
 * 获取图片地址
 * @param  [type] $arr [description]
 * @return [type]      [description]
 */
function get_img_src($url,$type=''){
	if(!preg_match("/\.com/i", $url,$arr)){
		echo '/data/upload/'.$url;
	}else{
		echo $url.$type;
	}
}































/**
 *
 *
 *
 *
 *
 *
 *
 
 
 
 
 
 
 
 *
 *
 *
 *
 *
 *
 *
 *
 * 
 */
/**
 * 1
 * 根据广告名称获取广告内容
 * @param string $ad
 * @return 广告内容
 */

function sp_getad($ad){
	$ad_obj=new AdModel();
	$ad=$ad_obj->field("ad_content")->where("ad_name='$ad'")->find();
	return $ad['ad_content'];
}

/**
 * 2
 * 根据幻灯片标识获取所有幻灯片
 * @param string $slide 幻灯片标识
 * @return array;
 */
function sp_getslide($slide){
	$slide_obj=new SlideCatModel();
	$join = "".C('DB_PREFIX').'slide as b on '.C('DB_PREFIX').'slide_cat.cid =b.slide_cid';
	return $slide_obj->join($join)->where("cat_idname='$slide'")->select();

}

/**
 * 3
 * 获取所有友情连接
 * @return array
 */
function sp_getlinks(){
	$links_obj=new LinksModel();
	return  $links_obj->where("link_status=1")->select();
}


/**
 * 4
 * @处理标签函数
 * @以字符串方式传入,通过sp_param_lable函数解析为以下变量
 * ids:调用指定ID的一个或多个数据,如 1,2,3
 * cid:数据所在分类,可调出一个或多个分类数据,如 1,2,3 默认值为全部,在当前分类为:'.$cid.'
 * field:调用post指定字段,如(id,post_title...) 默认全部
 * limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)
 * order:推荐方式(post_date) (desc/asc/rand())
 */
function sp_sql_posts($tag){
	// echo $tag;
	// exit;
	$where=array();
	$tag=sp_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '';
	$order = !empty($tag['order']) ? $tag['order'] : 'post_date';


	//根据参数生成查询条件
	$where['status'] = array('eq',1);
	$where['post_status'] = array('eq',1);

	if (isset($tag['cid'])) {
		$where['term_id'] = array('in',$tag['cid']);
	}
	
	if (isset($tag['ids'])) {
		$where['object_id'] = array('in',$tag['ids']);
	}


	$join = "".C('DB_PREFIX').'posts as b on a.object_id =b.ID';
	$join2= "".C('DB_PREFIX').'users as c on b.post_author = c.ID';
	$rs=new TermRelationshipsModel();

	$posts=$rs->alias("a")->join($join)->join($join2)->field($field)->where($where)->order($order)->limit($limit)->select();
	return $posts;
}

/**
 * 4
 * @ 处理标签函数
 * @ $tag以字符串方式传入,通过sp_param_lable函数解析为以下变量。例："cid:1,2;order:post_date desc,listorder desc;"
 * ids:调用指定ID的一个或多个数据,如 1,2,3
 * cid:数据所在分类,可调出一个或多个分类数据,如 1,2,3 默认值为全部,在当前分类为:'.$cid.'
 * field:调用post指定字段,如(id,post_title...) 默认全部
 * limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)
 * order:推荐方式(post_date) (desc/asc/rand())
 */

function sp_sql_posts_paged($tag,$pagesize=20,$pagetpl='{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}'){
	$where=array();
	$tag=sp_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '';
	$order = !empty($tag['order']) ? $tag['order'] : 'post_date';


	//根据参数生成查询条件
	$where['status'] = array('eq',1);
	$where['post_status'] = array('eq',1);

	if (isset($tag['cid'])) {
		$where['term_id'] = array('in',$tag['cid']);
	}

	if (isset($tag['ids'])) {
		$where['object_id'] = array('in',$tag['ids']);
	}

	$join = "".C('DB_PREFIX').'posts as b on a.object_id =b.ID';
	$join2= "".C('DB_PREFIX').'users as c on b.post_author = c.ID';
	$rs=new TermRelationshipsModel();
	$totalsize=$rs->alias("a")->join($join)->join($join2)->field($field)->where($where)->count();
	
	import('Page');
	if ($pagesize == 0) {
		$pagesize = 20;
	}
	$PageParam = C("VAR_PAGE");
	$page = new Page($totalsize,$pagesize);
	$page->setLinkWraper("li");
	$page->SetPager('default', $pagetpl, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
	$posts=$rs->alias("a")->join($join)->join($join2)->field($field)->where($where)->order($order)->limit($page->firstRow . ',' . $page->listRows)->select();

	$content['posts']=$posts;
	$content['page']=$page->show('default');
	return $content;
}



/**
 * 5
 * @param int $tid 分类表下的tid.
 * @param string $tag 
 * @处理标签函数
 * @以字符串方式传入,通过sp_param_lable函数解析为以下变量
 * field:调用post指定字段,如(id,post_title...) 默认全部
 * 如：field:post_title;
 * @return array 返回指定id所有页面
 */
function sp_sql_post($tid,$tag){
	$where=array();
	$tag=sp_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';


	//根据参数生成查询条件
	$where['status'] = array('eq',1);
	$where['tid'] = array('eq',$tid);


	$join = "".C('DB_PREFIX').'posts as b on a.object_id =b.ID';
	// $join2= "".C('DB_PREFIX').'users as c on b.post_author = c.ID';
	$rs=new TermRelationshipsModel();

	$posts=$rs->alias("a")->join($join)->join($join2)->field($field)->where($where)->find();
	return $posts;
}

/**
 * 6
 * @处理标签函数
 * @以字符串方式传入,通过sp_param_lable函数解析为以下变量
 * 返回符合条件的所有页面
 * ids:调用指定ID的一个或多个数据,如 1,2,3
 * field:调用post指定字段,如(id,post_title...) 默认全部
 * limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)
 * order:推荐使用方式(post_date) (desc/asc/rand())
 * 使用：ids:1,2;field:post_date,post_content;limit:10;order:post_date DESC,ID;
 */
function sp_sql_pages($tag){
	$where=array();
	$tag=sp_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '';
	$order = !empty($tag['order']) ? $tag['order'] : 'post_date';


	//根据参数生成查询条件
	$where['post_status'] = array('eq',1);
	$where['post_type'] = array('eq',2);

	$rs=new PostsModel();

	$posts=$rs->field($field)->where($where)->order($order)->limit($limit)->select();
	return $posts;
}

/**
 * 7
 * @处理标签函数
 * @以字符串方式传入,通过sp_param_lable函数解析为以下变量
 * 返回指定ID=$ID的页面
 */
function sp_sql_page($ID){
	$where=array();
	$where['ID'] = array('eq',$ID);

	$rs=new PostsModel();

	$post=$rs->where($where)->find();
	return $post;
}


/**
 * 8
 * 返回指定分类
 */
function sp_get_term($term_id){
	
	$terms=F('all_terms');
	if(empty($terms)){
		$term_obj=new TermsModel();
		$terms=$term_obj->where("status=1")->select();
		$mterms=array();
		
		foreach ($terms as $t){
			$tid=$t['term_id'];
			$mterms["t$tid"]=$t;
		}
		
		F('all_terms',$mterms);
		return $mterms["t$term_id"];
	}else{
		return $terms["t$term_id"];
	}
}
/**
 * 8
 * 返回指定分类下的子分类
 */
function sp_get_child_terms($term_id){

	$term_id=intval($term_id);
	$term_obj=new TermsModel();
	$terms=$term_obj->where("status=1 and parent=$term_id")->select();
	
	return $terms;
}
/**
 * 9
 * @处理标签函数
 * @以字符串方式传入,通过sp_param_lable函数解析为以下变量
 * 返回符合条件的所有分类
 * ids:调用指定ID的一个或多个数据,如 1,2,3
 * field:调用post指定字段,如(id,post_title...) 默认全部
 * limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)
 * order:path (desc/asc/rand())
 * 使用：ids:1,2;field:post_date,post_content;limit:10;order:post_date DESC,ID;
 */
function sp_get_terms($tag){
	
	$where=array();
	$tag=sp_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '';
	$order = !empty($tag['order']) ? $tag['order'] : 'term_id';
	
	//根据参数生成查询条件
	$where['status'] = array('eq',1);
	
	if (isset($tag['ids'])) {
		$where['term_id'] = array('in',$tag['ids']);
	}
	
	$term_obj=new TermsModel();
	$terms=$term_obj->field($field)->where($where)->order($order)->limit($limit)->select();
	return $terms;
}